const gameBox = document.querySelector('.game-box')
const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')

let tooltip = document.getElementById('tooltip');
let loadingText = document.querySelector('.loading-text')
let loginBox = document.querySelector('.login-box')
let serverBox = document.querySelector('.server-box')
let dialogBox = document.querySelector('.dialog-box')

canvas.width = config.canvasWidth
canvas.height = config.canvasHeight

let isShowNotice = false // 是否展示公告

let mapGx = config.mapGridX // 地图横坐标格子个数
let mapGy = config.mapGridY // 地图纵坐标格子个数

let animationId = null 
let frameAnimationId = null 
let boundaries = [] // 障碍物集合
let transferZones = [] // 传送区域
let collisions = [] // 障碍物和地图集合
const offset = { // 地图偏移量
  x: config.mapOffsetX,
  y: config.mapOffsetY
}
let timer = null
let overtimer = null
let loginTimer = null

let player = null // 人物数据

let currentMapData = maps[0] // 获取地图数据

let playerPos = {
  x: 0,
  y: 0
}

let background = {}
let foreground = {}

let renderables = []
let isLoadMap = false
let isConnectSocket = !config.isOnline
let isLogin = false

loadingText.innerHTML = messageText.loading

// 创建登录界面
function createLoginLayout ()
{
  c.clearRect(0, 0, canvas.width, canvas.height)
  const loginBgImgae = new Image();
  loginBgImgae.src = config.publicPath + '/assets/ui/login/bg.png'
  const loginBg = new Sprite({
    position: {
      x: offset.x,
      y: offset.y
    },
    image: loginBgImgae
  })
  const loginLogoImgae = new Image();
  loginLogoImgae.src = config.publicPath + '/assets/ui/login/MoleLogo.png'
  const loginLogo = new Sprite({
    position: {
      x: offset.x + 20,
      y: offset.y + 20
    },
    image: loginLogoImgae,
    scale: 0.6
  })
  const loginPaopaoImgae = new Image();
  loginPaopaoImgae.src = config.publicPath + '/assets/ui/login/paopao.png'
  const loginPaopao = new Sprite({
    position: {
      x: canvas.width / 2,
      y: 90
    },
    image: loginPaopaoImgae,
    scale: 0.6
  })
  loginBgImgae.onload = () => {
    // loginBg.draw()
    console.log('加载完成');
    loadingText.innerHTML = ''
    loginBox.style.display = 'block'
  }
  loginTimer = setInterval(() => {
    loginBg.draw()
    loginLogo.draw()
    loginPaopao.draw()
  }, 100);
}

// 创建服务器选择界面
function createServerSelectLayout ()
{
  loginBox.style.display = 'none'
  serverBox.style.display = 'flex'
}

// 隐藏弹框
function hideDialog ()
{
    dialogBox.style.display = 'none'
    gameBox.style.pointerEvents = 'all'
    dialogBox.children[0].innerHTML = ''
}

// 创建弹框
function createDialog (text, options)
{
  const { 
    showConifrmButton = false,
    showCancelButton = false,
    showYesButton = false,
    showImg = true,
    showClose = false,
    imgSrc = config.publicPath + '/assets/dialog/default.png'
  } = options
  const dialogText = document.querySelector('.dialog-text')
  const dialogImg = document.querySelector('.dialog-img')
  const dialogButton = document.querySelectorAll('.dialog-shadow')
  const dialogConfirm = document.querySelector('.dialog-confirm')
  const dialogCancel = document.querySelector('.dialog-cancel')
  const dialogYes = document.querySelector('.dialog-yes')
  const dialogClose = document.querySelector('.dialog-close')
  dialogBox.style.display = 'block'
  gameBox.style.pointerEvents = 'none'
  dialogText.innerHTML = text
  if (showImg) {
    dialogImg.style.display = 'inline-block'
    dialogImg.src = imgSrc
  } else
  {
    dialogImg.style.display = 'none'
  }
  showConifrmButton ? dialogConfirm.style.display = 'block' : dialogConfirm.style.display = 'none'
  showCancelButton ? dialogCancel.style.display = 'block' : dialogCancel.style.display = 'none'
  showYesButton ? dialogYes.style.display = 'block' : dialogYes.style.display = 'none'
  showClose ? dialogClose.style.display = 'block' : dialogClose.style.display = 'none'
  return new Promise((resolve, reject) => {
    dialogClose.addEventListener('mouseenter', function() {
        dialogClose.src = config.publicPath + '/assets/dialog/close_hover.png'
        dialogClose.style.transform = 'scale(1.1)'
        if (!audio.Button.playing()) audio.Button.play()
    })
    dialogClose.addEventListener('mouseleave', function() {
        dialogClose.src = config.publicPath + '/assets/dialog/close.png'
        dialogClose.style.transform = 'scale(1)'
        audio.Button.stop()
    })
    dialogClose.addEventListener('mousedown', function() {
        dialogClose.src = config.publicPath + '/assets/dialog/close_down.png'
        dialogClose.style.transform = 'scale(1)'
    })
    dialogClose.addEventListener('mouseup', function() {
        dialogClose.src = config.publicPath + '/assets/dialog/close_hover.png'
        resolve('close')
        dialogClose.style.transform = 'scale(1.1)'
    })
    for (let i = 0; i < dialogButton.length; i++)
    {
        dialogButton[i].addEventListener('mouseenter', function(e) {
            if (i === 0)
            {
                // 确认
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/confirm_hover.png'
            }
            else if (i === 1)
            {
                // 取消
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/cancel_hover.png'
            }
            else if (i === 2)
            {
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/yes_hover.png'
                
            }
            dialogButton[i].style.transform = 'scale(1.1)'
            if (!audio.Button.playing()) audio.Button.play()
        })
        dialogButton[i].addEventListener('mouseleave', function() {
            if (i === 0)
            {
                // 确认
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/confirm.png'
            }
            else if (i === 1)
            {
                // 取消
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/cancel.png'
            }
            else if (i === 2)
            {
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/yes.png'
            }
            dialogButton[i].style.transform = 'scale(1)'
            audio.Button.stop()
        })
        dialogButton[i].addEventListener('mousedown', function() {
            if (i === 0)
            {
                // 确认
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/confirm_down.png'
            }
            else if (i === 1)
            {
                // 取消
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/cancel_down.png'
            }
            else if (i === 2)
            {
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/yes_down.png'
            }
            dialogButton[i].style.transform = 'scale(1)'
        })
        dialogButton[i].addEventListener('mouseup', function() {
            // 处理按钮事件
            if (i === 0)
            {
                // 确认
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/confirm_hover.png'
                resolve('confirm')
            }
            else if (i === 1)
            {
                // 取消
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/cancel_hover.png'
                resolve('cancel')
            }
            else if (i === 2)
            {
                dialogButton[i].children[0].src = config.publicPath + '/assets/dialog/yes_hover.png'
                resolve('yes')
            }
            dialogButton[i].style.transform = 'scale(1.1)'
        })
    }
  })
}

// 创建加载页面
function createLoadingLayout (callback)
{
  let progress = 0
  let loadingTimer = null
  loginTimer && clearInterval(loginTimer)
  c.clearRect(0, 0, canvas.width, canvas.height)
  const loadingBgImgae = new Image();
  loadingBgImgae.src = config.publicPath + '/assets/loading/loading_bg.png'
  const loadingDialogImgae = new Image();
  loadingDialogImgae.src = config.publicPath + '/assets/loading/loading_dialog.png'
  const loadingProgressImgae = new Image();
  loadingProgressImgae.src = config.publicPath + '/assets/loading/loading_progress.png'
  const loadingBg = new Sprite({
    position: {
      x: offset.x,
      y: offset.y
    },
    image: loadingBgImgae
  })
  const loadingDialog = new Sprite({
    position: {
      x: canvas.width / 2 - 300 * 1.4 / 2,
      y: canvas.height / 2 - 80 * 1.4 / 2
    },
    image: loadingDialogImgae,
    scale: 1.4
  })
  const loadingProgress = new Sprite({
    position: {
      x: canvas.width / 2 - 446 * 0.8 / 2,
      y: canvas.height / 2 - 26 * 0.8 / 2 - 15
    },
    image: loadingProgressImgae,
    scale: 0.8
  })
  const shadowBg = new Shadow({
    width:canvas.width,
    height:canvas.height,
    position: {
      x: offset.x,
      y: offset.y
    },
    color:'#101011bf'
  })
  const loadingPercent = new Progress({
    width:446 * 0.8,
    height:26 * 0.8,
    position: {
      x: canvas.width / 2 - 446 * 0.8 / 2,
      y: canvas.height / 2 - 26 * 0.8 / 2 - 15
    },
    color:'#f9d46b',
    percent:progress
  })
  const loadingText = new Text({
    position: {
      x: canvas.width / 2 - 300 * 1.4 / 2 + 210,
      y: canvas.height / 2 - 80 * 1.4 / 2 + 80
    },
    text:messageText.loading,
    font:'20px Arial'
  })
  setTimeout(() => {
    callback()
  }, 1000);
  loadingTimer = setInterval(() => {
    loadingBg.draw()
    shadowBg.draw()
    loadingDialog.draw()
    loadingProgress.draw()
    loadingText.draw()
    loadingPercent.percent = progress / 100
    loadingPercent.draw()
    progress += 3
    console.log(progress);
    if (progress >= 100 && isLoadMap && player)
    {
      loadingTimer && clearInterval(loadingTimer)
      c.clearRect(0, 0, canvas.width, canvas.height)
    //   callback()
    }
    else
    {
        if (progress > 100) {
          progress = 0
            // loadingTimer && clearInterval(loadingTimer)
            // c.clearRect(0, 0, canvas.width, canvas.height)
        }
    }
  }, 60);
}

// 创建当前地图
function createCurrentMap ()
{
  // loadJS(currentMapData.mapCollsions, function () {
    createCurrentMapFrames()
    collisions = collisionsData[`collisionsData${currentMapData.mapId}`]
    const collisionsMap = [] // 地图坐标
    for (let i = 0; i < collisions.length; i += mapGx) {
      collisionsMap.push(collisions.slice(i, mapGx + i))
    }
    // 生成障碍物信息
    collisionsMap.forEach((row, i) => {
      row.forEach((symbol, j) => {
        if (symbol === 1) { // 障碍物
          boundaries.push(
            new Boundary({
              position: {
                x: j * Boundary.width + offset.x,
                y: i * Boundary.height + offset.y
              }
            })
          )
        } else if (symbol !== 0) {
          // 传送位置
          transferZones.push(
            {
              Id: symbol,
              object:new Boundary({
                position: {
                  x: j * Boundary.width + offset.x,
                  y: i * Boundary.height + offset.y
                }
              })
            }
          )
        }
      })
    })
    console.log(transferZones);
    const backgroundImage = new Image()
    backgroundImage.src = currentMapData.mapBackground

    const foregroundImage = new Image()
    foregroundImage.src = currentMapData.mapForeground

    playerPos = { // 初始化人物的位置
      x: currentMapData.mapInitialPos.x,
      y: currentMapData.mapInitialPos.y
    }

    if (player) { // 更新初始位置
      player.position.x = playerPos.x
      player.position.y = playerPos.y
      newPlayerX = playerPos.x
      newPlayerY = playerPos.y
      player.toward = 'down'
      player.image = player.sprites.down
    }


    background = new Sprite({
      position: {
        x: offset.x,
        y: offset.y
      },
      image: backgroundImage
    })
    
    foreground = new Sprite({
      position: {
        x: offset.x,
        y: offset.y
      },
      image: foregroundImage
    })
    renderables = [
      background, ...boundaries
    ]
    let imageList = [backgroundImage, foregroundImage]
    let loadedImages = 0;
    imageList.forEach((item) => {
      item.addEventListener('load', function() {
        loadedImages++;
        if (loadedImages === imageList.length) {
          // 地图加载完毕 进行socket的连接
          receiveWebSocket()
          // send({ // 发送状态，创建玩家
          //   code: '1000',
          //   username:userInfo.username
          // })
          isLoadMap = true;
          timer = setInterval(() => {
            if (isLoadMap && isConnectSocket)
            {
              clearInterval(timer)
              clearTimeout(overtimer)
              loadingText.innerHTML = ''
              animate()
              if (!currentMapData.mapAudio.playing()) currentMapData.mapAudio.play()
              if (!isShowNotice)
              {
                // 弹出公告
                createDialog(
                messageText.noticeMsg, 
                {
                  showClose:true,
                  showImg:false,
                  imgSrc: '../assets/dialog/default1.png'
                }).then((result) => {
                    if (result === 'close') hideDialog()
                })
                isShowNotice = true
              }
            }
          }, 100);
          overtimer = setTimeout(() => {
            // 20秒后判定连接超时
            clearInterval(timer)
            clearTimeout(overtimer)
            loadingText.innerHTML = '连接超时，请刷新重试！'
          }, 20000);
        }
      })
    })
  // }) // 加载地图
}

// 创建当前地图里场景帧动画
function createCurrentMapFrames ()
{
  let currentMapFrames = currentMapData.frames
  if(!currentMapData.frames.length) return
  if(currentMapData.isLoadFrame) {
    currentMapData.frames.forEach((item) => {
      item.currentFrame = 0
    //   item.timer = setInterval(() => {
    //     drawFrame(item)
    //     item.currentFrame = (item.currentFrame + 1) % item.imgPaths.length;
    //   }, 60);
    })
    return
  }
  currentMapData.frames.forEach((item) => {
    for (let index = 0; index < item.frame; index++) {
      let path = config.publicPath + `/maps/${currentMapData.mapId}/frame/${item.id}/(${index+1}).png`
      // 将帧路径push进去数组保存
      item.imgPaths.push(path)
    }
    const images = [];
    let imagesLoaded = 0;
    item.imgPaths.forEach((path, index) => {
      const img = new Image();
      img.src = path;
      img.onload = () => {
        images[index] = img;
        imagesLoaded++;
        if (imagesLoaded === item.imgPaths.length) {
          currentMapData.isLoadFrame = true
          // 所有图片加载完成后开始动画
          item.currentFrame = 0
          item.images = images
          // item.timer = setInterval(() => {
          //   drawFrame(item)
          //   item.currentFrame = (item.currentFrame + 1) % item.imgPaths.length;
          // }, 60);
        }
      };
    })
  })
}

// createCurrentMap() // 创建地图

// 加载人物不同动作
const playerDownImage = new Image()
playerDownImage.src = config.publicPath + '/player/playerDown.png'

const playerUpImage = new Image()
playerUpImage.src = config.publicPath + '/player/playerUp.png'

const playerLeftImage = new Image()
playerLeftImage.src = config.publicPath + '/player/playerLeft.png'

const playerRightImage = new Image()
playerRightImage.src = config.publicPath + '/player/playerRight.png'

const keys = {
  w: {
    pressed: false
  },
  a: {
    pressed: false
  },
  s: {
    pressed: false
  },
  d: {
    pressed: false
  }
}

let isStopEvent = false // 是否停止键盘事件

let isBan = false

let lastRenderTime = 0; // 上一帧的时间戳
const frameInterval = 100; // 帧延时

function animate(timestamp) {
  animationId = window.requestAnimationFrame(animate)
  renderables.forEach((renderable) => {
    renderable.draw()
  })
  if (!lastRenderTime) {
    lastRenderTime = timestamp;
  }
  // 计算时间间隔
  const deltaTime = timestamp - lastRenderTime;
  currentMapData.frames.forEach((item) => {
    drawFrame(item)
    if (deltaTime > frameInterval) {
        // 更新上一帧的时间戳
        lastRenderTime = timestamp;
        item.currentFrame = (item.currentFrame + 1) % item.imgPaths.length;
    }
    // clearInterval(item.timer)
  })
  if (player) player.draw()
  if (playerList.length) {
    playerList.forEach((item) => {
      if (item.toward === 'down')
      {
        item.image = item.sprites.down
      }
      else if (item.toward === 'up')
      {
        item.image = item.sprites.up
      }
      else if (item.toward === 'right')
      {
        item.image = item.sprites.right
      }
      else if (item.toward === 'left')
      {
        item.image = item.sprites.left
      }
      item.draw();
    })
  }
  
  if (JSON.stringify(foreground) !== '{}') foreground.draw()
  let moving = true
  if (player) player.animate = false
  if (isStopEvent) return

  // 是否进入到跳转地图区域
  if (keys.w.pressed || keys.a.pressed || keys.s.pressed || keys.d.pressed) {
    if (player) player.isMove = true
    for (let i = 0; i < transferZones.length; i++) {
      const transferZone = transferZones[i]
      const overlappingArea =
        (Math.min(
          player.position.x + player.width,
          transferZone.object.position.x + transferZone.object.width
        ) -
          Math.max(player.position.x, transferZone.object.position.x)) *
        (Math.min(
          player.position.y + player.height,
          transferZone.object.position.y + transferZone.object.height
        ) -
          Math.max(player.position.y, transferZone.object.position.y))
      if (
        rectangularCollision({
          rectangle1: player, 
          rectangle2: transferZone.object
        }) &&
        overlappingArea > 900
      ) {
          console.log('进入跳转区域了', overlappingArea);
        // window.cancelAnimationFrame(animationId)
        // // 暂停音乐播放
        // currentMapData.mapAudio.stop()
        // isLoadMap = false
        // isStopEvent = true // 终止事件循环
        // 加载loading框
        // createLoadingLayout(() => {
          currentMapData.mapTransferList.forEach((item) => {
            if (item.Id === transferZone.Id)
            { 
              console.log('跳转到新地图', item.nextMapId);
              if (!findMapById(item.nextMapId))
              {
                // 当前区域未开放
                if (!isBan) {
                    createDialog('当前区域未开放！', {
                        showYesButton:true,
                        imgSrc: config.publicPath + '/assets/dialog/problem.png'
                    }).then((result) => {
                        if (result === 'yes') {
                            hideDialog()
                            isBan = true
                            setTimeout(() => {
                                isBan = false
                            }, 3000);
                        }
                    })
                }
              }
              else
              {
                window.cancelAnimationFrame(animationId)
                // 暂停音乐播放
                currentMapData.mapAudio.stop()
                isLoadMap = false
                isStopEvent = true // 终止事件循环
                boundaries = []
                transferZones = []
                // currentMapData.frames.forEach((item) => {
                //   item.currentFrame = 0
                //   // clearInterval(item.timer)
                // })
                createLoadingLayout(() => {
                    // 重新赋值，加载新地图

                    currentMapData = findMapById(item.nextMapId)
                    createCurrentMap()
                    isStopEvent = false
                })
              }
            }
          })
        // })
        break
      }
    }
  }

  if (keys.w.pressed && lastKey === 'w') {
 
    player.animate = true
    player.toward = 'up'
    player.image = player.sprites.up
    // 检测障碍物
    for (let i = 0; i < boundaries.length; i++) {
      const boundary = boundaries[i]
      if (
        rectangularCollision({
          rectangle1: player,
          rectangle2: {
            ...boundary,
            position: {
              x: boundary.position.x,
              y: boundary.position.y + 3
            }
          }
        })
      ) {
        moving = false
        break
      }
    }

    if (moving) {
      newPlayerY = newPlayerY - 3
      player.position.y -= 3
      if (playerList.length) {
        playerList.forEach((item) => {
          item.position.y += 3
        })
      }
    }
  } else if (keys.a.pressed && lastKey === 'a') {
    player.animate = true
    player.toward = 'left'
    player.image = player.sprites.left

    for (let i = 0; i < boundaries.length; i++) {
      const boundary = boundaries[i]
      if (
        rectangularCollision({
          rectangle1: player,
          rectangle2: {
            ...boundary,
            position: {
              x: boundary.position.x + 3,
              y: boundary.position.y
            }
          }
        })
      ) {
        moving = false
        break
      }
    }

    if (moving) {
      newPlayerX = newPlayerX - 3
      player.position.x -= 3
      if (playerList.length) {
        playerList.forEach((item) => {
          item.position.x += 3
        })
      }
    }
     
  } else if (keys.s.pressed && lastKey === 's') {
    player.animate = true
    player.toward = 'down'
    player.image = player.sprites.down
    for (let i = 0; i < boundaries.length; i++) {
      const boundary = boundaries[i]
      if (
        rectangularCollision({
          rectangle1: player,
          rectangle2: {
            ...boundary,
            position: {
              x: boundary.position.x,
              y: boundary.position.y - 3
            }
          }
        })
      ) {
        moving = false
        break
      }
    }

    if (moving) {
      newPlayerY = newPlayerY + 3
      player.position.y += 3
      if (playerList.length) {
        playerList.forEach((item) => {
          item.position.y -= 3
        })
      }
    }
      
  } else if (keys.d.pressed && lastKey === 'd') {
    player.animate = true
    player.toward = 'right'
    player.image = player.sprites.right

    for (let i = 0; i < boundaries.length; i++) {
      const boundary = boundaries[i]
      if (
        rectangularCollision({
          rectangle1: player,
          rectangle2: {
            ...boundary,
            position: {
              x: boundary.position.x - 3,
              y: boundary.position.y
            }
          }
        })
      ) {
        moving = false
        break
      }
    }

    if (moving) {
      newPlayerX = newPlayerX + 3
      player.position.x += 3
      if (playerList.length) {
        playerList.forEach((item) => {
          item.position.x -= 3
        })
      }
    }
      
  }
}

let lastKey = ''
window.addEventListener('keydown', (e) => {
  if (!isLoadMap) return
  if (player && player.isInteracting) {
    switch (e.key) {
      case ' ':
        player.interactionAsset.dialogueIndex++

        const { dialogueIndex, dialogue } = player.interactionAsset
        if (dialogueIndex <= dialogue.length - 1) {
          document.querySelector('#characterDialogueBox').innerHTML =
            player.interactionAsset.dialogue[dialogueIndex]
          return
        }

        // finish conversation
        player.isInteracting = false
        player.interactionAsset.dialogueIndex = 0
        document.querySelector('#characterDialogueBox').style.display = 'none'

        break
    }
    return
  }

  switch (e.key) {
    case ' ':
      if (!player.interactionAsset) return

      // beginning the conversation
      const firstMessage = player.interactionAsset.dialogue[0]
      document.querySelector('#characterDialogueBox').innerHTML = firstMessage
      document.querySelector('#characterDialogueBox').style.display = 'flex'
      player.isInteracting = true
      break
    case 'w':
      keys.w.pressed = true
      lastKey = 'w'
      break
    case 'a':
      keys.a.pressed = true
      lastKey = 'a'
      break

    case 's':
      keys.s.pressed = true
      lastKey = 's'
      break

    case 'd':
      keys.d.pressed = true
      lastKey = 'd'
      break
  }
})

function cancelMove () {
  if (keys.w.pressed)
  {
    lastKey = 'w'
  }
  else if (keys.a.pressed)
  {
    lastKey = 'a'
  }
  else if (keys.s.pressed)
  {
    lastKey = 's'
  }
  else if (keys.d.pressed)
  {
    lastKey = 'd'
  }
}

window.addEventListener('keyup', (e) => {
  // if (!isLoadMap) return
  switch (e.key) {
    case 'w':
      keys.w.pressed = false
      cancelMove()
      break
    case 'a':
      keys.a.pressed = false
      cancelMove()
      break
    case 's':
      keys.s.pressed = false
      cancelMove()
      break
    case 'd':
      keys.d.pressed = false
      cancelMove()
      break
  }
})


let clicked = false

function controlAudioPlay ()
{
  if (!clicked && isLoadMap && isConnectSocket) {
    if (currentMapData.mapAudio.playing()) return
    currentMapData.mapAudio.play() // 播放背景音乐
    clicked = true
  }
}
window.addEventListener('click', controlAudioPlay)


// 防抖函数
function debounce(func, delay) {
  let timer;
  return function() {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, arguments);
    }, delay);
  };
}

function handleMouseMove (e)
{
  if (!isLoadMap) return
  let rect = canvas.getBoundingClientRect();
  let x = e.clientX - rect.left;
  let y = e.clientY - rect.top;
  console.log(x, y);
  // return
  let zone;
  let transferList = currentMapData.mapTransferList

  for (let i = 0; i < transferList.length; i++)
  {
    if (x > transferList[i].pos[0] && x < transferList[i].pos[1] && y > transferList[i].pos[2] && y < transferList[i].pos[3])
    {
      zone = transferList[i]
      tooltip.style.display = 'block';
      tooltip.style.top = (y + 20) + 'px';
      if (x + 130 > canvas.width)
      {
        tooltip.style.left = x - 100 + 'px';
      }
      else
      {
        tooltip.style.left = (x + 30) + 'px';
      }
      tooltip.innerHTML = zone.name;
      canvas.style.cursor = 'pointer';
      break;
    }
  }
  if (!zone)
  {
      tooltip.style.display = 'none';
      tooltip.innerHTML = '';
      canvas.style.cursor = '';
  }

  let eventsList = currentMapData.events
  
}

const debouncedMouseMove = debounce(handleMouseMove, 60); 

window.addEventListener('beforeunload', (event) => {
  window.cancelAnimationFrame(animationId) // 关闭动画
  currentMapData.mapAudio.stop() // 暂停背景音乐
  window.removeEventListener('click', controlAudioPlay)
});


canvas.addEventListener('mousemove', debouncedMouseMove, false)


canvas.addEventListener('mouseout', function() {
  tooltip.style.display = 'none';
  canvas.style.cursor = '';
}, false);

// 绘制帧动画
function drawFrame (item)
{
    if (item.images[item.currentFrame]) {
      c.drawImage(item.images[item.currentFrame], item.x, item.y, item.w, item.h);
    }
}



